import React from "react";
import './index.css'; // 导入样式


// 导入子组件
import Count from './components/Count'
import Tabs from './components/Tabs.js'
import Form from './components/Form.js'
import CommentList from './components/CommentList.js'

import { http } from './utils'
class Comment extends React.Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot',
      },
      {
        id: 2,
        name: '时间',
        type: 'time',
      },
    ],
    active: 'hot',
    list: []
  }
  // 数据持久化
  // // 初始化
  // componentDidMount() {
  //   const list = JSON.parse(localStorage.getItem('B-list') || '[]')
  //   this.setState({ list })
  // }
  // // 数据更新
  // componentDidUpdate() {
  //   localStorage.setItem('B-list', JSON.stringify(this.state.list))
  // }

  // 发起请求
  async componentDidMount() {
    const res = await http.get('/list')
    console.log(res);
    this.setState({
      list: res.data.reverse()
    })
  }
  // 发表评论
  handelChange = async (txt) => {
    // 模拟后端发请求
    const res = await http.post('/list', {
      author: 'shi',
      comment: txt,
      time: new Date('2021-10-10 09:09:00'),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 0,
    })
    console.log('post', res);
    // 数据更新
    const list = await http.get('/list')
    this.setState({
      list: list.data.reverse(),
    })
  }
  // 删除
  del = async (e, id) => {
    await http.delete(`/list/${id}`)
    // 更新数据
    const list = await http.get('/list')
    this.setState({
      list: list.data.reverse()
    })
  }
  // 点赞
  ChangeAtt = async (id, attitude) => {
    await http.patch(`/list/${id}`, { attitude: attitude });
    const list = await http.get('/list')
    this.setState({
      list: list.data.reverse(),
    })
  }
  // 排序
  Label = (type) => {
    if (type === 'hot') {
      this.setState({
        list: [...this.state.list.sort((a, b) => {
          return b.time.getTime() - a.time.getTime()
        })],
        active: type
      })
    } else {
      this.setState({
        list: [...this.state.list.sort((a, b) => {
          return a.time.getTime() - b.time.getTime()
        })],
        active: type
      })
    }
  }
  render() {
    return (
      <div className="comment-root">
        <div className="comment-container">
          {/* 评论数 */}
          <Count list={this.state.list}></Count>

          {/* 排序tab */}
          <Tabs tabs={this.state.tabs} active={this.state.active} Label={this.Label}></Tabs>

          {/* 发表评论区 */}
          <Form handelChange={this.handelChange}></Form>

          {/* 评论列表区 */}
          <CommentList list={this.state.list} ChangeAtt={this.ChangeAtt} del={this.del}></CommentList>
        </div>
      </div >
    )
  }
}

export default Comment